package com.zjb.demo.common.listener;

import com.mybatisflex.annotation.InsertListener;
import com.mybatisflex.annotation.UpdateListener;
import com.zjb.demo.common.domain.dto.BaseEntity;
import com.zjb.demo.common.domain.dto.LogicalDeletionEntity;
import com.zjb.demo.common.util.CastUtils;
import com.zjb.demo.common.util.SecurityUtils;

import java.util.Date;

/**
 * @author 庄佳彬
 * @since 2023/12/23 13:49
 */
public class BaseOnListener implements InsertListener, UpdateListener {
    @Override
    public void onInsert(Object baseEntity) {
        var entity = CastUtils.cast(baseEntity, BaseEntity.class);
        SecurityUtils.getLoginUser().ifPresent(it -> entity.setCreateBy(it.getUsername()));
        entity.setCreateTime(new Date());
        if (entity instanceof LogicalDeletionEntity logicalDeletionEntity) {
            logicalDeletionEntity.setDelFlag(null);
        }
    }

    @Override
    public void onUpdate(Object baseEntity) {
        var entity = CastUtils.cast(baseEntity, BaseEntity.class);
        entity.setUpdateTime(new Date());
        SecurityUtils.getLoginUser().ifPresent(it -> entity.setUpdateBy(it.getUsername()));
    }

    @Override
    public int order() {
        return 10;
    }
}
